<?php
namespace app\api\controller;

use app\api\model\PointsRecord;
use app\api\model\User;
use think\Controller;
use think\Exception;
use think\Request;
use think\Loader;
use app\common\utils\Redis;
use app\api\model\LoginModel;
// 公众号授权登录 注册
class Login extends Common
{
    
	//授权页面回调 到  获取微信用户信息和 openid
	public function getIndex(Request $request)
	{

		Loader::import('Wxchat.Api');
		// Loader::import('Redis.Redis');
		
		$callback_url=HOST_URL.'/login/auth';
		$invite_code = $request->param('invite_code','');
		if($invite_code)
		{
			$callback_url.='?invite_code='.$invite_code;
		}
		$wx_config = load_scope_config('weixin');

		//var_dump($wx_min_program_config);die;
		$wx_api = new \Api([
			'appId' => $wx_config['appid'],
			'appSecret' => $wx_config['app_secret'],
			'mchId' => $wx_config['mchid'],
			'key' => $wx_config['key']
		]);


		$url = $wx_api->get_authorize_url(\Api::SNSAPI_USERINFO,$callback_url);


       return  redirect($url);

	}
	
    //获取 用户 的 基本信息 和 openid
   public function getAuth(Request $request)
   {
	   Loader::import('Wxchat.Api');
	   $code = $request->param('code');

	   //file_put_contents('wx_login_auth.txt',$code);

	   if(empty($code))
	   {
		   throw new Exception('无法获取 Code');
	   }
	   $invite_code=$request->param('invite_code','');
	   $wx_config = load_scope_config('weixin');
	   $wx_api = new \Api([
		   'appId' => $wx_config['appid'],
		   'appSecret' => $wx_config['app_secret'],
		   'mchId' => $wx_config['mchid'],
		   'key' => $wx_config['key']
	   ]);
	   
	   $res = $wx_api->get_userinfo_by_authorize(\Api::SNSAPI_USERINFO,$code);


	   if($res[0])
	   {
		   throw new Exception(json_encode($res[0]));
	   }

	   $this->assign('invite_code',$invite_code);

	   $wx_user_info = [
		   'openid'=>$res[1]->openid,
	         'nickname'=>$res[1]->nickname,
		   'avatar'=>$res[1]->headimgurl
	   ];

	   session('wx_userinfo',$wx_user_info);

	   return $this->fetch('register',['invite_code'=>$invite_code,'openid'=>$res[1]->openid]);
   }

 // 手机 密码登录
	public function  postLogin(Request $request)
	{
		$phone = $request->post('phone');
		$password = $request->post('password','');

		if (!check_valid_phone($phone)) {
			to_json_encode(400, '手机号格式不正确', ['status' => false]);

		}

		if(empty($password))
		{
			to_json_encode(400, '密码不能为空', ['status' => false]);

		}
		$password = encrypt_password($password);

		$info = LoginModel::getUserByPhone($phone);
		if(empty($info) || $info['user_passwd'] != $password)
		{
			to_json_encode(400, '账号不存在或密码错误', ['status' => false]);

		}
		
		$user_info = LoginModel::handleLoginUserInfo($info);
		session('user',$user_info);
		to_json_encode(200, 'success', $user_info);
		
	}

	public function postRegister(Request $request)
	{
		$wx_user_info = session('wx_userinfo');

		if(empty($wx_user_info))
		{
			to_json_encode(400, '无法获取微信Openid', ['status' => false]);
		}

		$user_name=$wx_user_info['nickname'];

		if($user_name)
		{
			$user_name = filter_emoji($user_name);
		}
		$openid = $wx_user_info['openid'];
		$avatar_url = $wx_user_info['avatar'];


		$phone = $request->post('phone');

		if (!check_valid_phone($phone)) {
			to_json_encode(400, '手机号格式不正确', ['status' => false]);

		}
		$verify_code = $request->post('verify_code');

		$redis = Redis::instance();
		$sess_verify_code = $redis->get(Utility::$sms_template[2].'_'.$phone);

		if ($sess_verify_code != $verify_code) {
			to_json_encode(400, '验证码错误', ['status' => false]);
		}
		$password = $request->post('password','');

//		$user_name = $request->post('nickname','','htmlspecialchars');
//
//		$avatar_url= $request->post('avatar_url','');
		if(empty($password))
		{
			to_json_encode(400, '密码不能为空', ['status' => false]);

		}

		$password = encrypt_password($password);
		$user_type = $request->post('type',0);

		//邀请码
		$invite_code = $request->post('invite_code','');
		$user_id = LoginModel::addUserWithPasswdAndType($phone, $openid, $user_name,$avatar_url, $password,$user_type);

		if(!$user_id)
		{
			to_json_encode(400, '该手机号已注册', ['status' => false]);

		}
		//注册用户添加 积分
		//同时在 userinfo 表中 添加 一条记录
		//若 不赠送积分，仍需 在 userinfo 表添加 一条记录
		//代理商不赠送积分

		if(!empty($invite_code))
		{
			if($user_type == 3)
			{
				$point_num =0;
			}else if($user_type == 2){
				// 直接甲方
				$point_num =PointsRecord::NUM_REGISTER_USER;
			}else{
				//设计院
				$point_num =PointsRecord::NUM_REGISTER_DESIGN;
			}
			if($point_num >0)
			{
				PointsRecord::incrUserPoints($user_id,PointsRecord::POINTS_REGISTER,0,$point_num);

			}else{
				User::incrUserPoints($user_id,$point_num);
			}
			//计算 积分
			$invite_user_id = User::getUserIdByInviteCode($invite_code);
			if($invite_user_id)
			{
				PointsRecord::handleInvitePoints($user_id,$invite_user_id);
			}
		}else{
			//添加一条 userinfo记录
			User::incrUserPoints($user_id,0);

		}
		\app\admin\model\UserModel::generateInviteCode($user_id);
		to_json_encode(200, 'success', ['status' => true]);
	}
	public function postFindPassword(Request $request)
	{
		$phone = $request->post('phone');
		$password = $request->post('password','');

		$verify_code = $request->post('verify_code');

		
		if (!check_valid_phone($phone)) {
			to_json_encode(400, '手机号格式不正确', ['status' => false]);

		}
		if(empty($password))
		{
			to_json_encode(400, '密码不能为空', ['status' => false]);

		}
		
		$redis = Redis::instance();
		$sess_verify_code = $redis->get(Utility::$sms_template[4].'_'.$phone);

		if ($sess_verify_code != $verify_code) {
			to_json_encode(400, '验证码错误', ['status' => false]);
		}
		
		$info = LoginModel::getUserByPhone($phone);
		if(empty($info))
		{
			to_json_encode(400, '账号不存在', ['status' => false]);

		}

		$password = encrypt_password($password);

		LoginModel::updateUserPassword($info['user_id'],$password);
		to_json_encode(200, 'success',['status'=>true]);
	}
	public function postLogout(Request $request)
	{
		session('user',null);
	}
}
